package com.base.study.activity;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.base.commonlib.resh.SmartRefreshLayout;
import com.base.commonlib.resh.api.RefreshLayout;
import com.base.commonlib.resh.footer.ClassicsFooter;
import com.base.commonlib.resh.header.ClassicsHeader;
import com.base.commonlib.resh.listener.OnRefreshLoadmoreListener;
import com.base.commonlib.widget.RightDrawEditText;
import com.base.study.R;
import com.base.study.adapter.ForTyoeAdapter;
import com.base.study.bean.FromStudyTypeistBean;
import com.base.study.presenter.SubjectFromTypePresenter;
import com.base.study.view.SubjectFormTypeView;
import com.base.study.widget.RecyclerViewSpacesItemDecoration;

import java.util.ArrayList;
import java.util.List;


/**
 * 搜索
 */

public class SearchPopWindow extends PopupWindow implements View.OnClickListener, SubjectFormTypeView {
    private SmartRefreshLayout smartRefreshLayout;
    private ForTyoeAdapter forTyoeAdapter;
    private List<FromStudyTypeistBean> mData = new ArrayList<>();
    private RecyclerView rv_subject_list;
    private ImageView empty;
    private RightDrawEditText search;
    private TextView cancel;
    private RelativeLayout lin_root;
    private Animation animationIn, animationOut;
    private boolean isDismiss = false;
    private SubjectFromTypePresenter mPresenter;
    private String mid;
    private Integer page = 1;
    private String mSecondCategoryName;

    public SearchPopWindow(Context context, Activity activity, String id, String secondCategoryName) {
        super(context);
        this.mid = id;
        this.mSecondCategoryName = secondCategoryName;
        View inflate = LayoutInflater.from(context).inflate(R.layout.popwindow_search, null);
        this.setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        this.setHeight(LinearLayout.LayoutParams.MATCH_PARENT);
        this.setBackgroundDrawable(new ColorDrawable());
        this.setFocusable(true);
        this.setOutsideTouchable(true);
        this.update();
        this.setBackgroundDrawable(new ColorDrawable());
        this.setContentView(inflate);
        animationIn = AnimationUtils.loadAnimation(context, R.anim.up_in1);
        animationOut = AnimationUtils.loadAnimation(context, R.anim.down_out1);
        search = (RightDrawEditText) inflate.findViewById(R.id.search);
        cancel = (TextView) inflate.findViewById(R.id.cancel);
        lin_root = (RelativeLayout) inflate.findViewById(R.id.lin_root);
        smartRefreshLayout = (SmartRefreshLayout) inflate.findViewById(R.id.smartRefreshLayout);
        rv_subject_list = (RecyclerView) inflate.findViewById(R.id.rv_subject_list);
        empty = (ImageView) inflate.findViewById(R.id.empty);
        cancel.setOnClickListener(this);
        mPresenter = new SubjectFromTypePresenter(this, activity);
        forTyoeAdapter = new ForTyoeAdapter(context, activity, mData, mSecondCategoryName);
        forTyoeAdapter.setShowHead(false);
        forTyoeAdapter.isHead(0);
        smartRefreshLayout.setRefreshHeader(new ClassicsHeader(context));
        smartRefreshLayout.setHeaderHeight(60);
        smartRefreshLayout.setRefreshFooter(new ClassicsFooter(context));
        rv_subject_list.setAdapter(forTyoeAdapter);

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        rv_subject_list.setLayoutManager(linearLayoutManager);
        rv_subject_list.addItemDecoration(new RecyclerViewSpacesItemDecoration
                (10, 10, 10, 10));

        smartRefreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                mPresenter.getList(page, 10, mid, "");
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page = 1;
                mPresenter.getList(page, 10, mid, "");
            }
        });

        search.setOnTextChangedListener(new RightDrawEditText.OnTextChangedListener() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence text, int start, int lengthBefore, int lengthAfter) {
                if (!TextUtils.isEmpty(text)) {
                    mPresenter.getList(page, 10, mid, text.toString());
                } else {
                    if (mData != null) {
                        mData.clear();
                    }
                    forTyoeAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    public void setHint(String str) {
        if (search != null) {
            search.setHint(str);
        }
    }

    @Override
    public void showAsDropDown(View parent) {

        try {
            if (Build.VERSION.SDK_INT >= 24) {
                int[] location = new int[2];
                parent.getLocationOnScreen(location);
                int x = location[0];
                int y = location[1] + parent.getHeight();
                this.showAtLocation(parent, Gravity.BOTTOM, x, y);
            } else {
                this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            }
            showSoft(search);
            isDismiss = false;
            lin_root.startAnimation(animationIn);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void dismiss() {
        if (isDismiss) {
            return;
        }
        isDismiss = true;
        lin_root.startAnimation(animationOut);
        dismiss();
        animationOut.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                isDismiss = false;
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.JELLY_BEAN) {
                    dismiss4Pop();
                } else {
                    SearchPopWindow.super.dismiss();
                }
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
            }
        });
    }

    /**
     * 在android4.1.1和4.1.2版本关闭PopWindow
     */
    private void dismiss4Pop() {
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                SearchPopWindow.super.dismiss();
            }
        });
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.cacle) {
            dismiss();
        }
        dismiss();
    }

    /**
     * 显示键盘
     *
     * @param text 输入焦点
     */
    private void showSoft(final EditText text) {
        Handler handle = new Handler();
        handle.postDelayed(new Runnable() {

            @Override
            public void run() {
                InputMethodManager inputMethodManager = (InputMethodManager) text.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(text, 0);
            }
        }, 0);
    }


    @Override
    public void returnNoData() {
        smartRefreshLayout.finishRefresh();
        empty.setVisibility(View.VISIBLE);
    }

    @Override
    public void returnList(List<FromStudyTypeistBean> bean) {
        empty.setVisibility(View.GONE);
        smartRefreshLayout.finishRefresh();
        smartRefreshLayout.setLoadmoreFinished(false);
        mData.clear();
        mData.addAll(bean);
        if (forTyoeAdapter != null) {
            forTyoeAdapter.setShowHead(true);
            forTyoeAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void returnMoreList(List<FromStudyTypeistBean> bean) {
        empty.setVisibility(View.GONE);
        smartRefreshLayout.finishLoadmore();
        smartRefreshLayout.setLoadmoreFinished(false);
        mData.addAll(bean);
        if (forTyoeAdapter != null) {
            forTyoeAdapter.setShowHead(true);
            forTyoeAdapter.notifyDataSetChanged();
        }

    }

    @Override
    public void returnNoMoreData() {
        empty.setVisibility(View.GONE);
        forTyoeAdapter.setShowHead(true);
        smartRefreshLayout.finishLoadmore();
        smartRefreshLayout.setLoadmoreFinished(true);
    }

    @Override
    public void returnError() {
        empty.setVisibility(View.GONE);
        if (page == 1) {
            smartRefreshLayout.finishRefresh();
        } else {
            smartRefreshLayout.finishLoadmore();
        }
    }

    @Override
    public void showPb() {

    }

    @Override
    public void hidePb() {

    }

    @Override
    public void showMes(String msg) {

    }

    @Override
    public void showMes_action(String msg, String action, View.OnClickListener listener) {

    }

    @Override
    public void showError() {

    }

    @Override
    public void showPb_mes(String mes) {

    }

    @Override
    public void hidePb_mes() {

    }

    @Override
    public void onLogin() {

    }
}
